package com.xiaoluyy.rpc.wrapper;

import com.xiaoluyy.rpc.annotion.ThriftController;
import com.xiaoluyy.rpc.config.ThriftRpcService;
import com.xiaoluyy.rpc.config.ThriftRpcServiceConfig;
import com.xiaoluyy.rpc.properties.ThriftServerProperties;
import com.xiaoluyy.rpc.exception.ThriftServerException;
import com.xiaoluyy.rpc.exception.ThriftServerInstantiateException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.transport.TTransportException;
import org.apache.thrift.transport.TTransportFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.TargetSource;
import org.springframework.aop.framework.Advised;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
@EnableConfigurationProperties(ThriftServerProperties.class)
public class ThriftServerAutoConfiguration implements ApplicationContextAware {

    private static final Logger LOGGER = LoggerFactory.getLogger(ThriftServerAutoConfiguration.class);

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Bean
    @ConditionalOnMissingBean
    public ThriftRpcService thriftServerGroup(ThriftServerProperties properties) throws TTransportException, IOException {
        String[] beanNames = applicationContext.getBeanNamesForAnnotation(ThriftController.class);
        if (beanNames.length == 0) {
            LOGGER.error("Can't search any thrift controller annotated with @ThriftController");
            throw new ThriftServerException("Can not found any thrift controller");
        }

        List<ThriftRpcServiceConfig> thriftRpcServiceConfigs = Arrays.stream(beanNames).distinct().map(beanName -> {
            Object bean = applicationContext.getBean(beanName);
            Object target = bean;

            ThriftController thriftController = bean.getClass().getAnnotation(ThriftController.class);
            String thriftServiceName = StringUtils.isEmpty(thriftController.value()) ? beanName : thriftController.value();
            if (target instanceof Advised) {
                TargetSource targetSource = ((Advised) target).getTargetSource();
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Target object {} uses cglib proxy");
                }
                try {
                    target = targetSource.getTarget();
                } catch (Exception e) {
                    throw new ThriftServerInstantiateException("Failed to get target bean from " + target, e);
                }
            }
            return new ThriftRpcServiceConfig(Boolean.parseBoolean(properties.getRegisterFlag()),target.getClass().getName(),target);
        }).collect(Collectors.toList());
        ThriftRpcService thriftRpcService = adaptThriftRpcService(properties);
        thriftRpcService.setServiceConfigList(thriftRpcServiceConfigs);
        return thriftRpcService;
    }

    @Bean
    @ConditionalOnMissingBean
    public ThriftServerBootstrap thriftServerBootstrap(ThriftRpcService thriftRpcService) {
        return new ThriftServerBootstrap(thriftRpcService);
    }



    private ThriftRpcService adaptThriftRpcService(ThriftServerProperties properties) {
        TTransportFactory transportFactory = null;
        TProtocolFactory protocolFactory = null;

        String transportFactoryName = properties.getTransportFactoryName();
        if (org.apache.commons.lang.StringUtils.isBlank(transportFactoryName) || transportFactoryName.equals("TTransportFactory")) {
            transportFactory = new TTransportFactory();
        }

        String protocolFactoryName = properties.getProtocolFactoryName();
        if (org.apache.commons.lang.StringUtils.isBlank(protocolFactoryName) || protocolFactoryName.equals("TBinaryProtocol")) {
            protocolFactory = new TBinaryProtocol.Factory();
        }
        String serverType = properties.getServerType();
        ThriftRpcService thriftRpcService = new ThriftRpcService(transportFactory, protocolFactory, serverType);
        thriftRpcService.setServerType(properties.getServerType());
        thriftRpcService.setThriftServiceName(properties.getName());
        return thriftRpcService;

    }
}
